/**
 * 函数防抖
 * @param {function} func 传入函数
 * @param {number} wait 表示时间窗口的间隔
 * @param {boolean} immediate 设置为ture时，调用被包装函数时，立即执行
 * @return {function} 返回客户调用函数
 */
const debounce = (func, wait, immediate) => {
  let timeout;
  return function () {
    let context = this;
    let args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }
}

/**
 * 函数节流
 * @param {function} func 传入函数
 * @param {number} wait 表示时间窗口的间隔
 * @return {function} 返回客户调用函数
 */
const throttle = (func, wait) => {
  let previous = 0;
  return function () {
    let now = Date.now();
    let context = this;
    let args = arguments;
    if (now - previous > wait) {
      func.apply(context, args);
      previous = now;
    }
  }
}
/**
 * 对象转化成query
 * @param {Object} payload  传入对象 {a:1,b:2}
 * @return {String} 返回字符串 ?a=1&b=2
 */

const objectConvertToQuery = (payload) => {
  let queryStr = '?',
    i = Object.keys(payload).length
  if (!payload) {
    queryStr = ''
  }
  Object.keys(payload).forEach((key, index) => {
    if (i === (index + 1)) {
      queryStr += (key + '=' + payload[key])
    } else {
      queryStr += (key + '=' + payload[key] + '&')
    }
  })
  return queryStr
}

/**
 * url 转 query
 * @param {String} url  传入 字符串 ?a=1&b=2 
 * @return {Object} 返回 对象 {a:1,b:2}
 */
function urlConvertObjext(url) {
  let newurl = url.split("?");
  let oldarray = newurl[1].split("&"); 
  let strToObj = {};
  for (let i = 0; i < oldarray.length; i++) {
    let arritem = oldarray[i];
    let item = arritem.split("=");
    strToObj [item[0]] = item[1];
  }
  return strToObj ;
}

function formatDate(dateStr) {
  dateStr = dateStr.replace(/-/g,"/")
  const date = new Date(dateStr);
  const now = new Date();
  const y = date.getFullYear(), m = date.getMonth(), d = date.getDate()
  const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
  if (y == now.getFullYear() && m == now.getMonth() && d == now.getDate()) {
    return `${supplement(date.getHours())}:${supplement(date.getMinutes())}`;
  } else if(y == yesterday.getFullYear() && m == yesterday.getMonth() && d == yesterday.getDate()) {
    return "昨天"
  } else if (y == now.getFullYear()) {
    return `${supplement(m + 1)}/${supplement(d)}`;
  } else {
    return `${y}/${supplement(m + 1)}/${supplement(d)}`;
  }
}

function supplement (value,len=2,symbol="0") {
  value = value + ""
  return value.padStart(len,symbol)
}

module.exports = {
  debounce,
  throttle,
  objectConvertToQuery,
  urlConvertObjext,
  formatDate
}